<?php
namespace My\Model;

class UserRole {

	protected $roles = array();

	protected $code = array(); // 二进制的倒序

	/**
	 * 用户类型码
	 * @param unknown $typeCode
	 * @return \My\Model\UserRole
	*/
	public function type( $typeCode ) {
		$roleStr = decbin($typeCode);
		$arr = array();
		for ( $i=0; $i < strlen($roleStr) ; $i++ ) {
			$arr[] = substr($roleStr, $i, 1)*1; // 倒序取值
		}
		$arr = array_reverse($arr);
		$this->code = $arr;
		$this->roles = $this->getUserRoles( $typeCode );
		return $this;
	}

	/**
	 * 是{$type}角色
	 * @param unknown $type
	 * @return boolean
	 */
	public function is( $type ) {
		return in_array($type, $this->roles);
	}

	/**
	 * 不是{$type}角色
	 * @param unknown $type
	 * @return boolean
	 */
	public function isNot( $type ) {
		return !in_array($type, $this->roles);
	}

	/**
	 * 成为{$type}
	 * @param unknown $type
	 */
	public function becomeTo( $type ) {
		for( $i = 0; $i < $type; $i++ ) {
			if( !isset($this->code[$i]) ) { // 补0
				$this->code[$i] = 0;
			}
		}
		$this->code[$type] = 1;
		return $this;
	}

	/**
	 * 清除{$type}
	 * @param unknown $type
	 */
	public function clearTo( $type ) {
		for( $i = 0; $i < $type; $i++ ) {
			if( !isset($this->code[$i]) ) { // 补0
				$this->code[$i] = 0;
			}
		}
		$this->code[$type] = 0;
		return $this;
	}

	/**
	 * 获得type值
	 * @param unknown $type
	 */
	public function getType() {
		$arr = array_reverse($this->code);
		$string = implode('', $arr);
		return bindec($string);
	}


	/**
	 * 通过用户类型特征码得到用户类型的所有id值
	 * @param int $type
	 * 例如: 7=111 分别对应  金牌会员/代理商/普通会员
	 */
	public function getUserRoles( $type = 0 ) {
		if ( $type ) {
			$roleStr = decbin($type);
			$roles = array();
			for ( $i=strlen($roleStr)-1; $i >= 0 ; $i-- ) {
				$roleFlag = substr($roleStr, $i, 1)*1; // 倒序取值
				$j = strlen($roleStr)-1-$i; // 倒序索引
				if ( $roleFlag*1 ) {
					$roles[] = $j;
				}
			}
			return $roles;
		}
		return $this->roles;
	}
}